package com.hsmpay.qian4.service.ds.impl;

import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.account.scanCodePay.MD5;
import com.hsmpay.mobile.action.account.scanCodePay.ScanCodePayParam;
import com.hsmpay.mobile.action.account.scanCodePay.SignUtils;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.service.ds.JQSecondPayService;
import com.hsmpay.utils.DesUtil;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.system.ConConfig;
import javapns.org.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("ds_JQSecondPayService")
public class JQSecondPayServiceImpl implements JQSecondPayService{

    public static WriteFile wf = new WriteFile("ds_JQSecode");
    private static Logger log = LoggerFactory.getLogger(JQSecondPayServiceImpl.class);
    private static final String requestIp = "127.0.0.1";//请求方公网IP
    public static String urlStr = ConConfig.getAttribute("URL_OFFICIAL");

    /**
     * 获取消费二维码
     * @param scanCodePayParam
     * @return
     * @throws Exception
     */
    public PurchaseResult getQRCode(ScanCodePayParam scanCodePayParam, User user,Integer appClient) throws Exception {

        PurchaseResult pr = new PurchaseResult();
        pr.setReqMsg("获取交易订单失败,请稍后再试!");
        pr.setStatus(0);
        pr.setReqCode("0001");

        //商户未报备,不能走此通道,否则无法结算
        if(null == user || StringUtils.isBlank(user.getJQCusId()) || StringUtils.isBlank(user.getJQMD5Key())){
            pr.setReqMsg("交易异常,商户未报备!");
            return pr;
        }

        String notifyUrl = "http://"+urlStr+"/proOneMobile/JQNotify.action";
        String reqUrl = "http://app.1spay.com/agent/transReq.action";

        String outTradeNo = scanCodePayParam.getOutTradeNo();
        double totalFee = Double.valueOf(scanCodePayParam.getTotalFee());

        log.info("【进钱-秒到收款 请求参数】outTradeNo: "+ outTradeNo);
        log.info("【进钱-秒到收款 请求参数】totalFee: "+ totalFee);

        wf.log("【进钱-秒到收款 请求参数】outTradeNo: "+outTradeNo, "调试");
        wf.log("【进钱-秒到收款 请求参数】totalFee: "+totalFee, "调试");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(date);
        String reqDate = dateStr.substring(0,8);
        String reqTime = dateStr.substring(8);

        SortedMap<String,String> map = new TreeMap<>();

        if(appClient == 1){//AliPay
            map.put("version", "1.0.0");
            map.put("service","0010");
        }else if(appClient == 2){//WeChart
            map.put("version", "2.0.0");
            map.put("service","0001");
            map.put("openId", scanCodePayParam.getSubOpenId());
        }else {
            pr.setReqMsg("暂不支持此平台,请在微信或支付宝内完成交易!");
            return pr;
        }

        map.put("reqDate", reqDate);
        map.put("transAmount", String.valueOf(NumberUtil.roundF2(totalFee*100).longValue()));//金额转为分
        map.put("bgReturnUrl", notifyUrl);
        map.put("customerNo", user.getJQCusId());
        map.put("externalId", outTradeNo);
        map.put("selfData",DesUtil.generate32Key());
        map.put("requestIp", requestIp);
        map.put("description", scanCodePayParam.getBody());
        map.put("reqTime", reqTime);

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + user.getJQMD5Key(), "utf-8");
        map.put("sign", sign);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(map);

        JSONObject jsonObject = new JSONObject(paramMap);
        log.info("【进钱-秒到收款 请求参数】:" + jsonObject.toString());

        String responseUrl = "";

        if(ConConfig.isFormal()){
            wf.log("【进钱-秒到收款】请求环境:生产环境", "调试");

            CloseableHttpResponse response = null;
            CloseableHttpClient client = null;
            try {
                HttpPost httpPost = new HttpPost(reqUrl);
                StringEntity entityParams = new StringEntity(jsonObject.toString(), "utf-8");
                httpPost.setEntity(entityParams);
                httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                if (response != null && response.getEntity() != null) {
                    responseUrl = EntityUtils.toString(response.getEntity());
                    log.info("【进钱-秒到收款 响应参数】:" + responseUrl);
                    if(appClient == 1){//AliPay
                        JSONObject responseJson = new JSONObject(responseUrl);
                        String code = "";
                        if(responseJson.has("code")){
                            code = responseJson.getString("code");
                        }
                        String payUrl = "";
                        if(responseJson.has("payUrl")){
                            payUrl = responseJson.getString("payUrl");
                        }
                        if(code.equals("0") && StringUtils.isNotBlank(payUrl)){
                            responseUrl = payUrl;
                        }else {
                            responseUrl = "";
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("【进钱-秒到收款】 系统异常!");
                throw e;
            }
        }else {
            wf.log("【进钱-秒到收款】请求环境:测试环境", "调试");
            responseUrl = "http://app.aigopay.cn/agentTest/appIdPay.action?queryString=%7B%22payInfo%22%3A%7B%22appId%22%3A%22wxe00fda5293a2fa25%22%2C%22timeStamp%22%3A%221477549990077%22%2C%22signType%22%3A%22MD5%22%2C%22package%22%3A%22prepay_id%3Dwx2016102714331061665ffe0f0836315176%22%2C%22nonceStr%22%3A%221477549990077%22%2C%22paySign%22%3A%2217C153FC80EAFD4C4968CD70AAB37F5C%22%7D%7D";
            if(appClient == 1){
                responseUrl = "https://qr.alipay.com/bax02561tpzzbu1rstbi20fe";
            }
        }

        if(StringUtils.isNotBlank(responseUrl)){//业务受理成功
            pr.setPayUrl(responseUrl);//返回的支付地址
            pr.setCustomerNo(user.getJQCusId());
            pr.setReqMsg("获取交易订单成功!");
            pr.setReqCode("0000");
            pr.setStatus(1);
        }
        return pr;
    }

}
